package com.dragon.sdgp.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.*;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtil {

    private static final String SECRET = "SDGP";
    //token签发者
    private static final String ISSUSRE = "SDGP";
    //token过期时间
    public static final Long EXPIRE_DATE = 1000L * 60 * 60 * 24 * 7;    //7天过期

    /**
     * 生成token
     *
     * @param username
     * @return
     */
    public static String Token(String username) {
        //当前时间
        Date now = new Date();

        //1. header
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token = JWT.create()
                .withIssuer(ISSUSRE)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + EXPIRE_DATE))
                .withClaim("account", username)
//                .withClaim("id", admin.getId())
                .sign(algorithm);
        return token;
    }

    /**
     * 生成token
     *
     * @param map
     * @return
     */
    public static String createToken(Map<String, String> map) {
        //创建过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);  //7天过期

        //创建builder对象
        JWTCreator.Builder builder = JWT.create();
        //遍历map
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 验证token
     * 验证过程中如果有异常，则抛出；
     * 如果没有,则返回 DecodedJWT 对象来获取用户信息;
     *
     * @param token
     */
    public static DecodedJWT verifyToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        try {
            DecodedJWT verify = JWTUtil.verify(token);
            return verify;
        } catch (SignatureVerificationException e) {
            //验证的签名不一致
            throw new SignatureVerificationException(algorithm);
        } catch (TokenExpiredException e) {
            throw new TokenExpiredException("token is alreadey expired");
        } catch (AlgorithmMismatchException e) {
            throw new AlgorithmMismatchException("签名算法不匹配");
        } catch (InvalidClaimException e) {
            throw new InvalidClaimException("校验的claims内容不匹配");
        }  catch (JWTDecodeException e) {
            throw new JWTDecodeException("未知解析错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证token
     * 验证过程中如果有异常，则抛出；
     * 如果没有,则返回 DecodedJWT 对象来获取用户信息;
     *
     * @param token
     */
    private static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    public static String decode(String token){
        return verifyToken(token).getClaim("account").asString();
    }
}

